<template>
    <div class="workable-workablePlan-container">
        <el-card shadow="hover" class="mb10" v-auth="'workable:plan:list'">
			<el-input size="small" v-model="search.planName" placeholder="请输入计划名称" prefix-icon="el-icon-search" style="max-width: 180px;" class="ml10"></el-input>
            <el-date-picker size="small" type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="ml10"></el-date-picker>
            <el-button size="small" icon="el-icon-search" type="primary" class="ml10" @click="onTableSearch()">查询</el-button>
            <el-button size="small" icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'workable:plan:add'" size="small" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddWorkablePlan()">新增</el-button>
            <el-button v-auth="'workable:plan:edit'" size="small" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditWorkablePlan()" :disabled="tableData.selections.length != 1">修改</el-button>
            <el-button v-auth="'workable:plan:remove'" size="small" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
            <el-table ref="tableWorkablePlanRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
				<el-table-column label="计划名称" prop="planName" show-overflow-tooltip></el-table-column>
                <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip></el-table-column>
				<el-table-column label="版本号" prop="version" show-overflow-tooltip width="100"></el-table-column>
				<el-table-column label="cron表达式" prop="expression" show-overflow-tooltip></el-table-column>
                <el-table-column label="状态" prop="status" show-overflow-tooltip width="100">
					<template #default="scope">
						<span v-if="scope.row.status == '1'" class="color-success">运行中</span>
						<span v-else class="color-info">未运行</span>
					</template>
				</el-table-column>
                <el-table-column label="上一次调度时间" prop="lastTime" show-overflow-tooltip :formatter="onLongDateFormat"></el-table-column>
                <el-table-column label="下一次调度时间" prop="nextTime" show-overflow-tooltip :formatter="onLongDateFormat"></el-table-column>
                <el-table-column label="创建者" prop="createBy" show-overflow-tooltip width="120"></el-table-column>
                <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip width="150"></el-table-column>
                <el-table-column label="操作" show-overflow-tooltip width="125"
					v-auths="['workable:plan:stop', 'workable:plan:start', 'workable:plan:edit', 'workable:plan:remove']">
                    <template #default="scope">
						<el-button v-auth="'workable:plan:stop'" v-if="scope.row.status == '1'" size="mini" type="text" @click="onOpenStopWorkablePlan(scope.row)">停止</el-button>
                        <el-button v-auth="'workable:plan:start'" v-else size="mini" type="text" @click="onOpenStartWorkablePlan(scope.row)">启动</el-button>
						<el-button v-auth="'workable:plan:edit'" v-if="scope.row.status != '1'" size="mini" type="text" @click="onOpenEditWorkablePlan(scope.row)">修改</el-button>
                        <el-button v-auth="'workable:plan:remove'" v-if="scope.row.status != '1'" size="mini" type="text" @click="onTabelRowDel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                background
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddWorkablePlan ref="addWorkablePlanRef" @submit="onTableSearch"/>
        <EditWorkablePlan ref="editWorkablePlanRef" @submit="onTableSearch"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddWorkablePlan from '/@/views/workable/plan/addWorkablePlan.vue';
import EditWorkablePlan from '/@/views/workable/plan/editWorkablePlan.vue';
import { getWorkablePlanList, delWorkablePlan, startWorkablePlan, stopWorkablePlan } from '/@/api/workable/plan/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'workable/plan',
    components: { AddWorkablePlan, EditWorkablePlan },
    setup() {
        const tableWorkablePlanRef = ref();
        const addWorkablePlanRef = ref();
        const editWorkablePlanRef = ref();
        const state = reactive({
            search:{
				planName: undefined,
                startTime: undefined,
                endTime: undefined,
                pageNum: 1,
                pageSize: 10,
				orderBy: 'orderNum',
				isAsc: 'asc'
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData = (params) => {
            getWorkablePlanList(Object.assign(state.search, params)).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableWorkablePlanRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
			state.search.planName = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
		//Long时间转换成人类可读时间
		const onLongDateFormat = (row, column, cellValue, index) => {
			if(cellValue != null && cellValue != 0){
				return formatDate(new Date(cellValue), 'yyyy-MM-dd HH:mm:ss');
			}else{
				return cellValue;
			}
		}
        // 打开新增弹窗
        const onOpenAddWorkablePlan = (row: object) => {
            addWorkablePlanRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditWorkablePlan = (row: object) => {
            row = row || state.tableData.selections[0];
            editWorkablePlanRef.value.openDialog(row);
        };
		//启动
		const onOpenStartWorkablePlan = (row: object) => {
			const ids = row ? [row.id] : state.tableData.selections.map(item => item.id);
			if(ids && ids.length > 0){
				ElMessageBox.confirm('确定启动选中的计划信息吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}).then(() => {
					startWorkablePlan(ids).then((res) => {
						if(res.code === 0){
							ElMessage.success('启动成功');
							loadTableData();
						}
					});
				}).catch(() => {});
			}
		}
		//停止
		const onOpenStopWorkablePlan = (row: object) => {
			const ids = row ? [row.id] : state.tableData.selections.map(item => item.id);
			if(ids && ids.length > 0){
				ElMessageBox.confirm('确定停止选中的计划信息吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}).then(() => {
					stopWorkablePlan(ids).then((res) => {
						if(res.code === 0){
							ElMessage.success('启动成功');
							loadTableData();
						}
					});
				}).catch(() => {});
			}
		}
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的计划信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delWorkablePlan(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData();
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条计划信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delWorkablePlan([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData();
                    }
                });
            }).catch(() => {});
        };
        // 页面加载时
        onMounted(() => {
            loadTableData();
        });
        return {
            tableWorkablePlanRef,
            addWorkablePlanRef,
            editWorkablePlanRef,
            onTableSearch,
            onResetSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
			onLongDateFormat,
            onOpenAddWorkablePlan,
            onOpenEditWorkablePlan,
			onOpenStartWorkablePlan,
			onOpenStopWorkablePlan,
            onTabelRowsDel,
            onTabelRowDel,
            ...toRefs(state),
        };
    },
};
</script>